﻿using System;

namespace WeWork.Common
{
    /// <summary>
    /// 时间类
    /// </summary>
    public static class TimeHelper
    {
        /// <summary>
        /// 
        /// </summary>
        private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        /// <summary>
        /// 将时间转为10位和13位时间戳
        /// </summary>
        /// <param name="dt">时间</param>
        /// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳.bool bflag = true</param>
        /// <returns></returns>
        public static long GetDateTimeToUnixTime(DateTime dt, bool bflag = true)
        {
            var utcTime = dt.ToUniversalTime();
            var elapsedTime = utcTime - UnixEpoch;
            if (bflag)
            {
                return (long)elapsedTime.TotalSeconds;
            }
            else
            {
                return (long)elapsedTime.TotalMilliseconds;
            }
        }

        /// <summary>
        /// 将10位和13位时间戳转为时间
        /// </summary>
        /// <param name="unixTime">10位或13位时间戳</param>
        /// <returns></returns>
        public static DateTime GetUnixTimeToDateTime(string unixTime)
        {
            DateTime utcTime;
            long lTime = long.Parse(unixTime);
            if (unixTime.Length == 10)//判断是10位
            {
                utcTime = UnixEpoch.AddSeconds(lTime);
            }
            else if (unixTime.Length == 13)//判断是13位
            {
                utcTime = UnixEpoch.AddMilliseconds(lTime);
            }
            else
            {
                utcTime = UnixEpoch;
            }
            return utcTime.ToLocalTime(); ;

        }
    }
}
